/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/shortest-palindrome
   @Language: C++
   @Datetime: 20-01-08 14:52
   */


// KMP next, Time O(n), Space O(n)
class Solution {
public:
	string shortestPalindrome(string s) {
		int n=s.size();
		string rs(s);
		reverse(rs.begin(), rs.end());
		string srs = s+"#"+rs;
		vector<int> next(srs.size(), 0);
		for(int i=1, j; i<srs.size(); ++i){
			j = next[i-1];
			for(; j>0 && srs[i]!=srs[j]; j=next[j-1]);
			next[i] = j+(srs[i]==srs[j]);
		}
		return rs.substr(0, n-next.back())+s;
	}
};
